// EPropertyIPAddressA.cpp: implementation of the EPropertyIPAddressA class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include "others/EPropWndEdit.h"
#include "EPropertyIPAddressA.h"

using namespace std;

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

EPropertyIPAddressA::EPropertyIPAddressA(IPropertyHost *pHost, const std::wstring &sName, std::string *pProperty, bool bEnabled)
    : EIconTextButtonProperty(pHost, sName, pProperty, bEnabled)
{}

EPropertyIPAddressA::~EPropertyIPAddressA()
{}

bool EPropertyIPAddressA::HasEdit()
{
    return m_pProperty != NULL;
}

std::wstring EPropertyIPAddressA::GetTextValue()
{
    auto val = Utils::AsciiToWideByte(*((std::string *)m_pProperty));
    int i1 = 0;
    int i2 = 0;
    int i3 = 0;
    int i4 = 0;
    wchar_t c[256] = {};
    if(swscanf_s(val.c_str(), L"%3d.%3d.%3d.%3d", &i1, &i2, &i3, &i4) == 4) {
        auto &cmp = [](int val) {
            return 0 <= val && val <= 255;
        };
        if(cmp(i1) && cmp(i2) && cmp(i3) && cmp(i4)) {
            if(swprintf_s(c, 255, L"%d.%d.%d.%d", i1, i2, i3, i4) > 0) {
                if((wcscmp(val.c_str(), c) != 0)) {
                    *(std::string *)m_pProperty = Utils::WideByteToAscii(std::wstring(c));
                }
                return c;
            }
        }
    }

    return L"0.0.0.0";
}

bool EPropertyIPAddressA::OnPropApply()
{
    ASSERT(m_bSelected == true);
    ASSERT(m_pEdit != NULL);
    ASSERT(IsEnabled() == true);

    bool bPropertyChanged = false;

    int i1 = 0;
    int i2 = 0;
    int i3 = 0;
    int i4 = 0;

    wchar_t c[256];
    ::GetWindowTextW(m_pEdit->GetSafeHwnd(), c, 255);
    CStringW s(c);
    if(0 != wcscmp(s.GetString(), m_sInitialValueText.c_str())) {              //not the same
        if(swscanf_s(s, L"%3d.%3d.%3d.%3d", &i1, &i2, &i3, &i4) == 4) {
            auto &cmp = [](int val) {
                return 0 <= val && val <= 255;
            };
            if(cmp(i1) && cmp(i2) && cmp(i3) && cmp(i4)) {
                if(swprintf_s(c, 255, L"%d.%d.%d.%d", i1, i2, i3, i4) > 0 && (wcscmp(m_sInitialValueText.c_str(), c) != 0)) {
                    *(std::string *)m_pProperty = Utils::WideByteToAscii(std::wstring(c));
                    bPropertyChanged = true;
                }
            }
        }
    }

    return bPropertyChanged;
}